# Usage: transform.tcl
# In: 1900.orig.ps. Out: 1900.base.ps.
# Reads Part1 and replaces all water fills with W and all land fills with L.

package require Iexpect

cd [file dirname [info script]]

set I [iexpect::Expect #auto -white -file "1900.orig.ps" -encoding "iso8859-1"]
set you [open "1900.base.ps" w]
# Search for Part1.
$I expect line "^/Part1 \\\{$" {
	puts $you [$I get output]
	# Search for the list of Seas and replace the other definitions with simple ones for L, W and 0.
	$I expect line "/Seas \[\[\] ((\[0-9.\]+ )+)\[\]\] def" {
		set seas [$I get match 1]
		$I continue
	} "^CoastalBorder$" {
		puts $you ""
		puts $you "/L { gsave LandColor fill grestore stroke } bd"
		puts $you "/W { gsave SeaColor fill grestore stroke } bd"
		puts $you "/O /W ld"
		puts $you ""
		puts $you [$I get output]
	} default {
		$I continue
	}
	# Go through all following parts, replacing S with either L, W or O.
	set idx 0
	set partNr 0
	$I expect line "^\\\} bind def$" {
		puts $you [$I get output]
	} "^S$" {
		if {$idx == 0} {
			puts $you "O"
			incr idx
		} elseif {$idx < [llength $seas] && $partNr == [lindex $seas $idx]} {
			puts $you "W"
			incr idx
		} else {
			puts $you "L"
		}
		incr partNr
		$I continue
	} default {
		puts $you [$I get output]
		$I continue
	}
	$I continue
} default {
	puts $you [$I get output]
	$I continue
}
close $you
itcl::delete object $I
